<?php
/**
 * 文件管理控制类
 */

class fileManager extends control 
{
	private $dir;
	private $file;
	
	public function __construct(){
		parent::__construct();
		$this->dir = $this->loadModel('dir');
		$this->file = $this->loadModel('file');
		$load_lib = array('upload'=>'upload','image'=>'image');
		$this->loadClass($load_lib);

	}
	public function index(){}
	/**
	 * 获取目录树
	 *
	 */
	public function getDirTree(){
		$parnet_dir_id = $this->load->input->string('node');
		$this->dir->getDirTree($this->user_id,$parnet_dir_id);
	}
	/**
	 * 获取文件和文件夹
	 * 返回数组
	 * 
	 */
	public function getFileAndFolder(){
		$dir_id = $this->load->uri->getSeg(2);
		if(!$dir_id) $dir_id = '1'; 
		$rows = $this->file->getFileInDir($dir_id,$this->user_id);
		echo '{success:true,dir_id:'.$dir_id.',rows:'.json_encode($rows).'}';
	}
	/**
	 * 删除文件
	 * 
	 */
	public function removeTheFile() {
		$file_id = $this->load->input->int('file_id');
		$result = $this->file->delete($file_id);
		if($result) echo json_encode($result);
	}
	/**
	 * 文件的重命名
	 * 
	 */
	public function renameFileName() {
		//data filter
		$file_id = $this->load->input->int('file_id');
		$file_name = $this->load->input->string('file_name');
		$file_old_name = $this->load->input->string('file_old_name');
		$dir_id = $this->load->input->int('dir_id');
		
		//to_do:判断文件名是否合法
		
		if($file_id && $file_name && $file_old_name) {
			$ext = strrchr($file_name,'.');
			
			//如果文件扩展名不存在 则和$file_old_name的扩展名一样
			if(!$ext) {
				$ext = strrchr($file_old_name,'.');
				$file_name = $file_name.$ext;
			}
			
			//判断文件扩展名是否合法
			if(!in_array($ext,config::$file_ext)) {
				$data = array('success'=>true,'msg'=>'file_ext_not_valid');
				echo json_encode($data);
				return ;
			}
			
			//新文件名在$dir_id下是否存在 存在则退出
			$cond = array('file_name'=>$file_name,'user_id'=>$this->user_id,'dir_id'=>$dir_id);
			$is_file_exist = $this->file->find($cond);
			if($is_file_exist) {
				$data = array('success'=>true,'msg'=>'file_exist');
				echo json_encode($data);
				return ;
			}
			
			//更新文件名
			$cond = array('file_id'=>$file_id);
			$data = array('file_name'=>$file_name);	
			$result = $this->file->update($cond,$data);
			if($result) {
				$data = array('success'=>true,'msg'=>'ok','text'=>$file_name);
				echo json_encode($data);
			}
		}
	}
	
	public function simpleUpload() {
		$dir_id = $this->load->input->post('dir_id');
		if($dir_id == 'undefined') $dir_id = '7';
		$file_url = $this->load->upload->filesUpload('upload',$this->user_name,$dir_id,$user_id = $this->user_id);
		//$result = $this->load->image->createThumbnail($file_url);//生成缩略图
		if($result !== false) {
			echo '文件上传成功';
		}	
	
	}
}

?>
